﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace SqlServerDriver
{
	/*
		Class to hold in-memory data-tables referred to by history. 
		In particular the Quickdiff table, which can be expensive to build.
		Pressing the back button should be a quick experience.
		Note: using this creates resource releasing problems.
		      but only in expreme cases.
	*/ 
	class DataTableRepository
	{
		public static DataTableRepository Instance
		{
			get
			{
				if (theRepository == null)
					theRepository = new DataTableRepository();
				return theRepository;
			}
		}
		
		// hidden singleton constructor
		DataTableRepository()
		{
			this.tableStore = new Dictionary<int, DataTable>();
		}
		
		//
		// Note asymmetry between Set and Get.
		// Set takes ownership of the table while Get returns
		// a copy
		public int SetTable(DataTable tableToHold)
		{
			int freeId = 1;
			while (this.tableStore.ContainsKey(freeId))
				++freeId;
			this.tableStore.Add(freeId, tableToHold);
			return freeId;
		}
	
		public DataTable GetTable(int tableId)
		{
			if (!this.tableStore.ContainsKey(tableId)) return null; // not found. Clients please test for this.
			return this.TearOffTable(this.tableStore[tableId]);
		}

		private DataTable TearOffTable(DataTable dataTable)
		{
			DataTable dt = dataTable.Clone();
			foreach (DataRow dr in dataTable.Rows)
			{
				dt.ImportRow(dr);
			}
			// What about the extra information?
			return dt;
		}
	
		Dictionary<int, DataTable> tableStore;
		
		static DataTableRepository theRepository = null;
	}
}
